package com.android.process.messenger

import android.app.Service
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import com.android.lib.messenger.AndroidMessenger
import com.android.lib.messenger.MessageCallback

class TestService: Service() {
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        AndroidMessenger.subscribe("service", object : MessageCallback {
            override fun onMessageCallBack(data: Bundle?) {
                val text = data?.getString("test")
                Toast.makeText(this@TestService, text, Toast.LENGTH_SHORT).show()
                Log.e("35hwm", "TestService 接收到消息: $text")
            }
        })
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Handler().postDelayed({
            sendMsg()
        }, 200)
        return super.onStartCommand(intent, flags, startId)
    }

    private fun sendMsg() {
        val bundle = Bundle()
        bundle.putString("test", "TestService key:activity1 发送的消息")
        AndroidMessenger.post("ServiceToActivity1", bundle)
    }

    override fun onDestroy() {
        super.onDestroy()
        AndroidMessenger.unSubscribe("service")
    }
}